self.onmessage = async function (e) {
  const { file, chunkSize = 1024 * 1024 } = e.data // 默认1MB块大小

  const chapterRegex = /(^|\n)(第[一二三四五六七八九十百千万零]+章[^\n]*)/g
  const chapterIndex = []
  let offset = 0
  let remaining = ''

  try {
    while (offset < file.size) {
      const chunk = await readChunk(file, offset, chunkSize)
      const content = remaining + chunk

      let match
      while ((match = chapterRegex.exec(content)) !== null) {
        const chapterPosition = match.index + match[1].length
        chapterIndex.push({
          title: match[2].trim(),
          start: offset - remaining.length + chapterPosition,
          end: -1
        })
      }

      // 保留可能被截断的行
      const lastNewlineIndex = content.lastIndexOf('\n')
      if (lastNewlineIndex > 0 && offset + chunk.length < file.size) {
        remaining = content.slice(lastNewlineIndex)
        offset += chunk.length - (content.length - lastNewlineIndex)
      } else {
        remaining = ''
        offset += chunk.length
      }

      // 报告进度
      self.postMessage({
        type: 'progress',
        progress: Math.min(offset / file.size, 1)
      })
    }

    // 设置章节结束位置
    for (let i = 0; i < chapterIndex.length - 1; i++) {
      chapterIndex[i].end = chapterIndex[i + 1].start
    }
    if (chapterIndex.length > 0) {
      chapterIndex[chapterIndex.length - 1].end = file.size
    }

    self.postMessage({
      type: 'complete',
      chapterIndex
    })
  } catch (error) {
    self.postMessage({
      type: 'error',
      error: error.message
    })
  }
}

function readChunk (file, start, length) {
  return new Promise((resolve, reject) => {
    const blob = file.slice(start, start + length)
    const reader = new FileReader()
    reader.onload = e => resolve(e.target.result)
    reader.onerror = e => reject(new Error('读取文件块失败'))
    reader.readAsText(blob, 'UTF-8')
  })
}
